﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Ledict.Utility.Extension
{
    #region 获取字符串中指定HTML标签内容或去除HTML标签
    /// <summary>
    /// 描述：获取字符串中指定HTML标签内容或去除HTML标签
    /// 时间：2012-03-28
    /// 作者：张鹏
    /// </summary>
    public static class HtmlTagItemExtensions
    {
        /// <summary>
        /// 获取字符串中指定HTML标签内容
        /// </summary>
        /// <param name="HtmlTag"></param>
        /// <param name="HtmlText"></param>
        /// <param name="option"></param>
        /// <returns></returns>
        public static List<HtmlTagItem> GetHtmlTagProperty(string HtmlTag, string HtmlText, RegexOptions? option)
        {
            var list = new List<HtmlTagItem>();
            Match m = null;
            var o = option.HasValue ? option.Value : RegexOptions.IgnoreCase;


            m = new Regex(@"<" + HtmlTag + " [^<>]*>", o).Match(HtmlText);

            while (m != null && m.Value != null && m.Value.Length > 0)
            {
                var item = new HtmlTagItem()
                               {

                               };
                item.Tag = HtmlTag;
                item.Name = GetHtmlTagPropertyValue(m.Value, "name");
                item.ID = GetHtmlTagPropertyValue(m.Value, "id");
                item.Type = GetHtmlTagPropertyValue(m.Value, "type");
                item.Href = GetHtmlTagPropertyValue(m.Value, "href");
                item.Src = GetHtmlTagPropertyValue(m.Value, "src");
                item.Value = GetHtmlTagPropertyValue(m.Value, "value");
                item.Action = GetHtmlTagPropertyValue(m.Value, "action");
                item.Method = GetHtmlTagPropertyValue(m.Value, "method");
                list.Add(item);
                m = m.NextMatch();
            }
            return list;

        }


        public static string GetHtmlTagPropertyValue(string HtmlTagProperty, string PropertyName)
        {
            int idx = HtmlTagProperty.IndexOf(PropertyName, StringComparison.OrdinalIgnoreCase);
            string rtun = null;
            if (idx > -1)
            {
                byte state = 0;
                int pIdxS = -1;
                int pIdxE = -1;
                char bj = '\n';
                for (int i = idx; i < HtmlTagProperty.Length; i++)
                {
                    char c = HtmlTagProperty[i];
                    if (state == 00)
                    {
                        if (c == '=')
                        {
                            state = 1;
                        }
                    }
                    else if (state == 1)
                    {
                        if (bj == '\n')
                        {
                            if (c == ' ' && (HtmlTagProperty[i + 1] == ' ' || HtmlTagProperty[i + 1] == '"' || HtmlTagProperty[i + 1] == '\''))
                            {
                                continue;
                            }
                            if (c == ' ')
                            {
                                bj = ' ';
                                pIdxS = i + 1;
                            }
                            else if (c == '\'' || c == '"')
                            {
                                bj = c;
                                pIdxS = i + 1;
                            }
                            else
                            {
                                pIdxS = i;
                            }
                            state = 2;
                        }

                    }
                    else if (state == 2)
                    {
                        if (c == bj || c == '>')
                        {
                            pIdxE = i;
                            break;
                        }
                    }
                }
                if (pIdxE != -1 && pIdxS != -1 && pIdxE != pIdxS)
                {
                    rtun = HtmlTagProperty.Substring(pIdxS, pIdxE - pIdxS);
                }
            }
            return rtun;
        }


        /// <summary>
        /// 将Html标签转化为空格并去掉转换后的空格的字符串
        /// </summary>
        /// <param name="strHtml">待转化的字符串</param>
        /// <returns>经过转化的字符串</returns>
        public static string StripHtml(string strHtml)
        {
            var objRegExp = new Regex("<(.|\n)+?>");
            string strOutput = objRegExp.Replace(strHtml, "");
            strOutput = strOutput.Replace("<", "&lt;");
            strOutput = strOutput.Replace(">", "&gt;");
            //return strOutput;

            var r = new Regex(@"\s+");
            var wordsOnly = r.Replace(strOutput, " ");
            return wordsOnly.Trim();


        }

        /// <summary>
        /// 将Html标签中&nbsp转化为"'  ' br转化为/r/n"  add by zp
        /// </summary>
        /// <param name="strHtml"></param>
        /// <returns></returns>
        public static string ToNoHtml(this string strHtml)
        {

            string strOutput = strHtml;
            //strOutput = strOutput.Replace("<", "&lt;");
            //strOutput = strOutput.Replace(">", "&gt;");
            strOutput = strOutput.Replace("&nbsp;", "  ");
            //return strOutput;

            var r = new Regex(@"\s+");
            var wordsOnly = r.Replace(strOutput, " ");
            return wordsOnly.Trim();


            //return strHtml.Replace("&nbsp;", " ").Replace("<br/>", "/r/n");
        }


        /// <summary>
        /// 将所有HTML标签替换去除 add by zp
        /// </summary>
        /// <param name="strHtml"></param>
        /// <returns></returns>
        public static string StripHTMLstring(this string strHtml)
        {
            

            //删除脚本  
            strHtml = Regex.Replace(strHtml, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            //删除HTML  
            strHtml = Regex.Replace(strHtml, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            strHtml = Regex.Replace(strHtml, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            strHtml = Regex.Replace(strHtml, @"-->", "", RegexOptions.IgnoreCase);
            strHtml = Regex.Replace(strHtml, @"<!--.*", "", RegexOptions.IgnoreCase);

            strHtml = Regex.Replace(strHtml, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            strHtml = Regex.Replace(strHtml, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            strHtml = Regex.Replace(strHtml, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            strHtml = Regex.Replace(strHtml, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            strHtml = Regex.Replace(strHtml, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            strHtml = Regex.Replace(strHtml, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            strHtml = Regex.Replace(strHtml, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            strHtml = Regex.Replace(strHtml, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            strHtml = Regex.Replace(strHtml, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            strHtml = Regex.Replace(strHtml, @"&#(\d+);", "", RegexOptions.IgnoreCase);

            strHtml = strHtml.Replace("<br />", "\n")
                .Replace("<br />", "\n")
                
                .Replace("<", "")
                .Replace(">", "")
                .Replace("&nbsp;", " ")
                .Replace("&nbsp", " ");




            return strHtml;
        }






        #region 提取摘要，是否清除HTML
        /// <summary>
        /// 提取摘要，是否清除HTML代码
        /// </summary>
        /// <param name="content">文本内容</param>
        /// <param name="length">截取长度</param>
        /// <param name="StripHTML">是否去除HTML标记</param>
        /// <returns></returns>
        public static string GetContentSummary(string content, int length, bool StripHTML)
        {
            if (string.IsNullOrEmpty(content) || length == 0)
                return "";
            if (StripHTML)
            {
                var re = new Regex("<[^>]*>");
                content = re.Replace(content, "");
                content = content.Replace("　", "").Replace(" ", "");
                content = content.Replace("&nbsp;", "");
                content = content.Replace("&quot;", "");
                if (content.Length <= length)
                    return content;
                else
                    return content.Substring(0, length) + "……";
            }
            else
            {
                if (content.Length <= length)
                    return content;
                int pos = 0, npos = 0, size = 0;
                bool firststop = false, notr = false, noli = false;
                var sb = new StringBuilder();
                while (true)
                {
                    if (pos >= content.Length)
                        break;
                    string cur = content.Substring(pos, 1);
                    if (cur == "<")
                    {
                        string next = content.Substring(pos + 1, 3).ToLower();
                        if (next.IndexOf("p") == 0 && next.IndexOf("pre") != 0)
                        {
                            npos = content.IndexOf(">", pos) + 1;
                        }
                        else if (next.IndexOf("/p") == 0 && next.IndexOf("/pr") != 0)
                        {
                            npos = content.IndexOf(">", pos) + 1;
                            if (size < length)
                                sb.Append("<br/>");
                        }
                        else if (next.IndexOf("br") == 0)
                        {
                            npos = content.IndexOf(">", pos) + 1;
                            if (size < length)
                                sb.Append("<br/>");
                        }
                        else if (next.IndexOf("img") == 0)
                        {
                            npos = content.IndexOf(">", pos) + 1;
                            if (size < length)
                            {
                                sb.Append(content.Substring(pos, npos - pos));
                                size += npos - pos + 1;
                            }
                        }
                        else if (next.IndexOf("li") == 0 || next.IndexOf("/li") == 0)
                        {
                            npos = content.IndexOf(">", pos) + 1;
                            if (size < length)
                            {
                                sb.Append(content.Substring(pos, npos - pos));
                            }
                            else
                            {
                                if (!noli && next.IndexOf("/li") == 0)
                                {
                                    sb.Append(content.Substring(pos, npos - pos));
                                    noli = true;
                                }
                            }
                        }
                        else if (next.IndexOf("tr") == 0 || next.IndexOf("/tr") == 0)
                        {
                            npos = content.IndexOf(">", pos) + 1;
                            if (size < length)
                            {
                                sb.Append(content.Substring(pos, npos - pos));
                            }
                            else
                            {
                                if (!notr && next.IndexOf("/tr") == 0)
                                {
                                    sb.Append(content.Substring(pos, npos - pos));
                                    notr = true;
                                }
                            }
                        }
                        else if (next.IndexOf("td") == 0 || next.IndexOf("/td") == 0)
                        {
                            npos = content.IndexOf(">", pos) + 1;
                            if (size < length)
                            {
                                sb.Append(content.Substring(pos, npos - pos));
                            }
                            else
                            {
                                if (!notr)
                                {
                                    sb.Append(content.Substring(pos, npos - pos));
                                }
                            }

                        }
                        else
                        {
                            npos = content.IndexOf(">", pos) + 1;
                            sb.Append(content.Substring(pos, npos - pos));
                        }
                        if (npos <= pos)
                            npos = pos + 1;
                        pos = npos;
                    }
                    else
                    {
                        if (size < length)
                        {
                            sb.Append(cur);
                            size++;
                        }
                        else
                        {
                            if (!firststop)
                            {
                                sb.Append("……");
                                firststop = true;
                            }
                        }
                        pos++;
                    }
                }
                return sb.ToString();

            }

        }
        public static string GetContentSummary(string content)
        {
            if (string.IsNullOrEmpty(content))
                return "";
            var re = new Regex("<[^>]*>");
            content = re.Replace(content, "");
            content = content.Replace("　", "").Replace(" ", "");
            content = content.Replace("&nbsp;", "");
            content = content.Replace("&quot;", "");
            return content;
        }
        #endregion




    }

    #endregion




    /// <summary>
    /// HTML标签
    /// </summary>
    public class HtmlTagItem
    {
        public string Tag;
        public string Name;
        public string ID;
        public string Type;
        public string Action;
        public string Href;
        public string Src;
        public string Method;
        public string Value;
    }


}
